require('./reset.css')
require('./my-orders.less')
require('../../common/header/index.js')
var _order_service=require('service/order_service.js')
var _util=require('../../../util/util.js')
var orderListTemplate = require('./index.string')

var orders = {
  listData: {
    orderList: [],
  },

  init : function(){
    this.loadOrdersInfo();
    return this;
  },

  //向服务器发送请求，获取已登录账号的所有订单
  loadOrdersInfo: function(){
      _order_service.getOrderList(
        res => {     
          console.log(res);
          this.listData.orderList = res.data;
          var result = _util.renderHtml(orderListTemplate, {listData: this.listData});
          console.log(result);
          $('.orders').html(result);
          // for(let order of res.data){
          //   _order_service.getItemByOrderId(
          //     order.orderId,
          //     res => {
          //       //构造完整的order对象
          //       let obj = {};
          //       obj.order = order;
          //       obj.itemList = res.data;
          //       obj.len = res.data.length;

          //       this.listData.orderList.push(obj);
          //     },
          //     errMsg => {

          //     }
          //   )
          // }
          // console.log(this.listData);
          // debugger;


          
            // if(res.status===1)
            // return
            // var trAdd="";
            // res.data.forEach(function(item){
            //     trAdd+='<tr>';
            //     trAdd+='<td>'+item.orderId+'</td>';
            //     trAdd+='<td>'+item.orderDate+'</td>';
            //     trAdd+='<td>'+item.totalPrice+'11'+'</td>';
            //     trAdd+='<td>'+item.shipAddress1+'</td>';
            //     trAdd+='<td>'+item.status+'</td>';
            //     trAdd+='</td>';
            // })
            // $('#table').append(trAdd);
        },
        errMsg => { 
        }
      )
      // _order_service.check_cart(
    //   res => {  
    //     let cartItemList = res.data.itemList;
    //     //成功获取数据，进行数据的渲染
    //     this.listData.cartItemList = cartItemList;
    //     //购物车不为空才进行渲染
    //     if(cartItemList.length==0){
    //       $('.cart-body').html(`<b style="font-size:24px;">Your cart is empty.</b>`);
    //     }else{
    //       var result = _util.renderHtml(cartListTemplate, {listData: this.listData});
    //       $('.cart-body').html(result);
    //     }
        
    //     this.updateCartTool(cartItemList);
    //   },
    //   errMsg => {

    //   }
    // )    
  },

  //绑定事件
  bindEvents: function(){
    this.checkedChange();
    this.minusClicked();
    this.addClicked();
    this.quantityOnBlur();
    this.removeClicked();
    this.removeSelectedClicked();
    this.chooseAllClicked();
    this.checkoutClicked();
  },

  //为所有的checekbox绑定单击事件
  checkedChange: function(){
    let _this = this;
    $('.check-msg').each(function () {
      $(this).on('click', function () {
        let itemRow = this.parentNode.parentNode;
        let itemId = $(itemRow).attr('id');
        let checked = this.checked;

        _cart_service.change_checked(
          itemId,
          checked,
          res => {
            _this.updateCartTool(res.data.itemList);
          },
          errMsg => {

          }
        )
      });
    });
  },

  //为所有的-按钮绑定单击事件
  minusClicked: function(){
    let _this = this
    $('.mins').each(function () {
      $(this).on('click', function () {
        //获取相应的结点
        let quantityNode = this.nextSibling.nextSibling;
        let tempNode = this.parentNode.nextSibling.nextSibling;
        let listPriceNode = tempNode.firstChild.nextSibling;
        let totalPriceNode = tempNode.nextSibling.nextSibling.firstChild.nextSibling;
        let itemRow = this.parentNode.parentNode;

        //获取结点上的值
        let quantity = quantityNode.value;
        let listPrice = Number(listPriceNode.innerHTML.slice(1));
        let itemId = $(itemRow).attr('id');

        if (quantity > 1) {
          //修改商品数量和总价
          quantity--;
          totalPriceNode.innerHTML = '$' + (listPrice * quantity).toFixed(2);
          quantityNode.value = quantity;

          _this.updateQuantity(itemId, quantity);
        }
        else if (quantity == 1) {
          _this.removeItem(itemRow, itemId);
        }
      });
    });
  },

  //为所有的+按钮绑定单击事件
  addClicked: function(){
    let _this = this;
    $('.plus').each(function () {
      $(this).on('click', function () {
        //获取相应的结点
        let quantityNode = this.previousSibling.previousSibling;
        let tempNode = this.parentNode.nextSibling.nextSibling;
        let listPriceNode = tempNode.firstChild.nextSibling;
        let totalPriceNode = tempNode.nextSibling.nextSibling.firstChild.nextSibling;
        let itemRow = this.parentNode.parentNode;

        //获取结点上的值
        let quantity = quantityNode.value;
        let listPrice = Number(listPriceNode.innerHTML.slice(1));
        let itemId = $(itemRow).attr('id');

        //修改商品数量和总价
        quantity++;
        totalPriceNode.innerHTML = '$' + (listPrice * quantity).toFixed(2);
        quantityNode.value = quantity;

        _this.updateQuantity(itemId, quantity)
      });
    });
  },

  //为所有的input框绑定失去焦点事件
  quantityOnBlur: function(){
    let _this = this;
    $('.itxt').each(function () {
      $(this).on('blur', function () {
        //获取相应的结点
        let tempNode = this.parentNode.nextSibling.nextSibling;
        let listPriceNode = tempNode.firstChild.nextSibling;
        let totalPriceNode = tempNode.nextSibling.nextSibling.firstChild.nextSibling;
        let itemRow = this.parentNode.parentNode;

        //获取结点上的值
        let quantity = this.value;
        let listPrice = Number(listPriceNode.innerHTML.slice(1));
        let itemId = $(itemRow).attr('id');
        console.log(quantity);
        if (this.value > 0) {
          //修改总价
          totalPriceNode.innerHTML = '$' + (listPrice * quantity).toFixed(2);
          //发送ajax请求
          _cart_service.update_quantity(
            itemId, 
            quantity, 
            res => {
              _this.updateCartTool(res.data.itemList);
            }, 
            errMsg => {
  
            }
          );
        }
        else {
          _this.removeItem(itemRow, itemId);
        }
      });
    });
  },

  //为所有的删除按钮绑定单击事件
  removeClicked: function(){
    let _this = this;
    $('.sindelet').each(function () {
      $(this).on('click', function () {
          var itemRow = this.parentNode.parentNode;
          var itemId = $(itemRow).attr('id');

          //移除商品
          _this.removeItem(itemRow, itemId);
      });
    });
  },

  //为删除选中的商品绑定单击事件
  removeSelectedClicked: function(){
    let _this = this;
    $('#removeSelected').on('click', function(){
      $('.check-msg').each(function () {
        let checked = this.checked;
        if(checked){
          let itemRow = this.parentNode.parentNode;
          $(itemRow).remove();
        }
        var cartBody = $('.cart-body');
        if (cartBody.find('ul').length == 0) {
          $('.cart-body').html(`<b style="font-size:24px;">Your cart is empty.</b>`);
        }
        //向服务器发送请求
        _cart_service.remove_checked(
          res => {
            console.log(res);
            _this.updateCartTool(res.data.itemList);
          },
          errMsg => {

          }
        )
      });
    });
  },

  //为下方的全选checkbox绑定单击事件
  chooseAllClicked: function(){
    let _this = this;
    $('.chooseAll').on('click', function(){
      let checked = this.checked;
      $('.check-msg').each(function () {
        $(this).prop("checked",checked);
      });
      _cart_service.check_all(
        checked,
        res => {
          _this.updateCartTool(res.data.itemList);
        },
        errMsg => {

        }
      )
    });
  },
  
  //为结算绑定单击事件
  checkoutClicked: function(){
    $('.sum-btn').on('click', function(){
      //进行页面的跳转
      window.location.href = '../../view/cart/checkout.html';
    });
  },

  //移除一件商品
  removeItem: function(itemRow, itemId){
    $(itemRow).remove();
    var cartBody = $('.cart-body');
    if (cartBody.find('ul').length == 0) {
      $('.cart-body').html(`<b style="font-size:24px;">Your cart is empty.</b>`);
    }
    //发送ajax请求
    _cart_service.remove_cart(
      itemId, 
      res => {
        this.updateCartTool(res.data.itemList);
      }, 
      errMsg => {
        
      }
    );
  },

  //更新某件商品的数量
  updateQuantity: function(itemId, quantity){
    _cart_service.update_quantity(
      itemId, 
      quantity, 
      res => {
        this.updateCartTool(res.data.itemList);
      }, 
      errMsg => {

      }
    );
  },

  //更新cart下方的总结信息
  updateCartTool: function(cartItemList){
    //判断商品有没有被全选
    let flag = true;
    let count = 0;
    let subTotal = 0;
    for(let cartItem of cartItemList){
      if(!cartItem.checked){
        flag = false;
      }else{
        subTotal += cartItem.totalPrice;
        count++;
      }
    }
    var chooseAll = $('.chooseAll');
    chooseAll.prop("checked",flag);
    $('#countChoose').text(count);
    $('.summoney').text(`$${subTotal}`);
  },
};

module.exports = orders.init();